﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using Microsoft.Phone.Shell;
using System.ComponentModel;
using ArmyCreator.ViewModels;
using DataModel;
using WebCalls;
using ArmyCreator.Pages;
using System.Windows.Navigation;
using System.Threading.Tasks;

namespace ArmyCreator.UI
{
    public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged
    {
        private ProgressIndicator pi;


        public MainPage()
        {
            InitializeComponent();

            this.DataContext = UserContext.Instance;

            pi = new ProgressIndicator();
            pi.IsIndeterminate = true;
            pi.IsVisible = true;
            pi.Text = "Chargement des armées...";
            SystemTray.SetProgressIndicator(this, pi);

            UserContext.Instance.Listings.CollectionChanged += CollectionChanged;
        }

        private void CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            UpdateLastArmyState();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (!e.NavigationMode.Equals(NavigationMode.Back))
            {
                UpdateLastArmyState();

                retrieveListings();
            }
        }

        private void UpdateLastArmyState()
        {
            if (UserContext.Instance.Listings.Count > 0)
                VisualStateManager.GoToState(this, "LastArmyState", true);
            else
                VisualStateManager.GoToState(this, "NoLastArmyState", true);
        }

        private async void retrieveListings()
        {
            await RetrieveListings.Get("yenlui", "coucou");
            pi.IsVisible = false;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void GoToArmy(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Listing viewModel = null;

            if (sender is Control)
            {
                var control = (Control)sender;
                viewModel = (Listing)control.DataContext;
            }
            else if (sender is Grid)
            {
                var control = (Grid)sender;
                viewModel = (Listing)control.DataContext;
            }

            if (viewModel != null)
            {
                NavigationService.Navigate(new Uri("/Pages/" + typeof(ArmyPage).Name + ".xaml?id=" + viewModel.Army.Id, UriKind.Relative));
            }
        }
    }
}